/**
 * author:Administrator
 * date:2016/3/2
 * desc:TODO
 */
"use strict";

let Router = require('koa-router')
  , __pathPrefix = '/api/v1/role'
  , router = new Router({prefix: __pathPrefix});
module.exports = router.routes();
console.log('router:' + __pathPrefix + ',file=' + __filename);

let koabody = require('koa-better-body')();
let roleService = require('../../ddd/application/roleService.js');
let queryService = require('../../ddd/application/queryService');
let FormatOutput = require('../../common/FormatOutput.js');
let FormatError = require('../../common/FormatError.js');

/**
 * 获取登录用户 的 role
 * get /api/v1/role?uid=xx
 */
router.get('/', function*() {
  let uId = this.query.uid;
  let roles = yield queryService.allUserRole(uId);
  return this.body = new FormatOutput(0, null, roles);
});

/**
 * 用户选择一个role 做为登录role
 * get /api/v1/role/role/use?type=manager&id=1&uid=2
 */
router.get('/use', function*() {
  let type = this.query.type;
  let id = this.query.id;
  let uId = this.query.uid;
  let role = yield queryService.getRole(type, uId, id);
  if (role) role.type = type;

  this.body = FormatOutput.payloadOrError(role, FormatError.E_role_not_exist);
});

/**
 * 已登录用户,创建一个 customer
 * name,token,uid
 */
router.post('/customer', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let uId = fields.uid;
  let result = yield roleService.registerCustomer({name: name, uId: uId});
  this.body = FormatOutput.payloadOrError(result, FormatError.E_register_customer);
});

/**
 * 已登录用户,创建一个 vendor
 * name,token
 */
router.post('/vendor', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let uId = fields.uid;

  let result = yield roleService.registerVendor({name: name, uId: uId});
  this.body = FormatOutput.payloadOrError(result, FormatError.E_register_vendor);
});

/**
 * 已登录用户,创建一个 manager
 * name,token
 */
router.post('/manager', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let uId = fields.uid;
  let result = yield roleService.registerManager({name: name, uId: uId});
  this.body = FormatOutput.payloadOrError(result, FormatError.E_register_manager);

});

/**
 * 已登录用户,创建一个 shopkeeper
 * name,token
 */
router.post('/shopkeeper', koabody, function*() {
  let fields = this.request.body.fields;
  let name = fields.name;
  let obj = {name: name};

  let uId = fields.uid;
  if (uId) obj.uId = uId;

  let vendorId = fields.vendorid;
  if (vendorId) obj.vendorId = vendorId;
  console.log('create keeper',obj);
  let result = yield roleService.registerKeeper(obj);
  return this.body = FormatOutput.payloadOrError(result, FormatError.E_register_keeper);
});